package ochart.core.loaders
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import ochart.events.DataEvent;
	
	public class DataLoader extends EventDispatcher
	{
		public var url:String = null;
		public var data:Object = null;
		
		public function DataLoader(target:IEventDispatcher = null)
		{
			super(target);
		}
		
		public function load(url:String):void
		{
			this.url = url;
			
			var urlRequest:URLRequest = new URLRequest(url);
			var urlLoader:URLLoader = new URLLoader();
			urlLoader.addEventListener(ProgressEvent.PROGRESS, onProgress);
			urlLoader.addEventListener(Event.COMPLETE, onLoadComplete);
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
			urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
			urlLoader.load(urlRequest);
		}
		
		protected function onProgress(event:ProgressEvent):void
		{
			var dataEvent:DataEvent = new DataEvent(DataEvent.PROGRESS);
			dataEvent.bytesLoaded = event.bytesLoaded;
			dataEvent.bytesTotal = event.bytesTotal;
			dispatchEvent(dataEvent);
		}
		
		protected function onLoadComplete(event:Event):void
		{
			data = event.target.data;
			
			var dataEvent:DataEvent = new DataEvent(DataEvent.DATA);
			dataEvent.data = data;
			dispatchEvent(dataEvent);
		}
		
		protected function onIOError(event:IOErrorEvent):void
		{
			var dataEvent:DataEvent = new DataEvent(DataEvent.ERROR);
			dataEvent.error = "IO错误，具体错误信息:" + event.text;
			dispatchEvent(dataEvent);
		}
		
		protected function onSecurityError(event:SecurityErrorEvent):void
		{
			var dataEvent:DataEvent = new DataEvent(DataEvent.ERROR);
			dataEvent.error = "安全沙箱错误，具体错误信息:" + event.text;
			dispatchEvent(dataEvent);
		}
	}
}